/**
 * @author wenchi
 * @package google suggest
 */
(function($){
    /**
     * $ is an alias to jQuery object
     *
     */
    $.fn.suggest = function(settings){
        settings = jQuery.extend({
            uri: "jquery.search.suggest.php",
            id: "jquery-suggest",
            movein: "movein",
            moveout: "moveout",
            activeImage: 0
        }, settings);
        var _Obj = this;
        
        
        function _initialize(){
        
            settings.w = $(_Obj).css("width");
            
            settings.last = "";
            
            $(_Obj).after("<div id=\"" + settings.id + "\" style=\"width:" + settings.w + "; display:none; \"> </div>");
            
            //var de = document.documentElement;
            //var w = _Obj.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
            
            $("input , select ,textarea").css("z-index", "-1");
            //$("select").css("z-index","-1");
            
            //         alert(_getAbsoluteLeft($(_Obj).attr("id")));
            
            //				alert(_getAbsoluteTop($(_Obj).attr("id")));
            
            
            //alert(w);
            
            
            /*
             
             position:absolute;
             width:200px;
             height:115px;
             z-index:1;
             left: 594px;
             top: 184px;
             
             
             $results.css({
             width: parseInt(iWidth) + &quot;px&quot;,
             top: (pos.y + input.offsetHeight) + &quot;px&quot;,
             left: pos.x + &quot;px&quot;
             }).show();
             */
            settings.select = "n";
            
            if ($.browser.mozilla) 
                $(_Obj).keypress(_processKey); // onkeypress repeats arrow keys in Mozilla/Opera
            else 
                $(_Obj).keydown(_processKey); // onkeydown repeats arrow keys in IE/Safari
            return false;
        }
        
        function _getAbsoluteLeft(objectId){
            // Get an object left position from the upper left viewport corner
            o = document.getElementById(objectId)
            oLeft = o.offsetLeft // Get left position from the parent object
            while (o.offsetParent != null) { // Parse the parent hierarchy up to the document element
                oParent = o.offsetParent // Get parent object reference
                oLeft += oParent.offsetLeft // Add parent left position
                o = oParent
            }
            return oLeft
        }
        
        function _getAbsoluteTop(objectId){
            // Get an object top position from the upper left viewport corner
            o = document.getElementById(objectId)
            oTop = o.offsetTop // Get top position from the parent object
            while (o.offsetParent != null) { // Parse the parent hierarchy up to the document element
                oParent = o.offsetParent // Get parent object reference
                oTop += oParent.offsetTop // Add parent top position
                o = oParent
            }
            return oTop
        }
        
        
        function _findPos(obj){
            var curleft = obj.offsetLeft || 0;
            var curtop = obj.offsetTop || 0;
            
            while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft
                curtop += obj.offsetTop
            }
            
            return {
                x: curleft,
                y: curtop
            };
        }
        
        
        function _processKey(e){
        
            var reg = /(38|40|9|13|27)/;
            
            if (reg.test(e.keyCode)) {
            
                switch (e.keyCode) {
                
                    case 38: // up
                        //prevResult();
                        _prevtResult()
                        break;
                        
                    case 40: // down
                        //nextResult();
                        _nextResult();
                        break;
                        
                    case 9: // tab
                    case 13: // return	//	enter
                        //       selectCurrentResult();
                        _select($("#" + settings.id + " li." + settings.movein).html());
                        break;
                        
                    case 27: //	escape
                        //$results.hide();
                        $("#" + settings.id).hide();
                        break;
                        
                }
            }
            
            //alert(e.keyCode);
            //
            else 
                _respone();
            
            
        }
        
        function _nextResult(){
        
            var t = $("#" + settings.id + " li." + settings.movein);
            //alert(t.attr("id"));
            
            if (typeof(t.attr("id")) == "undefined") 
                var i = 0;
            else 
                var i = parseInt(t.attr("id"));
            //
            //alert(i);
            //alert(settings.total);
            
            if (i == 0) {
                _move(0, 1);
            }
            else 
                if ((settings.total - 1) == i) {
                    //      alert("=");
                    _move(i, 1);
                }
                else {
                    //      alert(i);
                    //      alert(i + 1);
                    //      alert("!=");
                    _move(i, (i + 1));
                }
            
            return false;
            
        }
        
        /*
         * @target 0
         * @target t
         */
        function _move(o, t){
        
            //return false;
            
            if (o > 0) 
                $("#" + settings.id + " ul li[id=" + o + "]").removeClass(settings.movein);
            
            if (t > 0) 
                $("#" + settings.id + " ul li[id=" + t + "]").addClass(settings.movein);
            
            
            return false;
            
        }
        
        function _prevtResult(){
        
            var t = $("#" + settings.id + " li." + settings.movein);
            if (typeof(t.attr("id")) == "undefined") 
                var i = 0;
            else 
                var i = parseInt(t.attr("id"));
            
            //			alert(i);
            //			alert(settings.total);
            
            if (i == 0) {
                _move(0, parseInt(settings.total) - 1);
            }
            else 
                if (i == 1) {
                    _move(1, parseInt(settings.total) - 1);
                //alert("=");
                }
                else {
                    _move(i, (i - 1));
                }
            
            return false;
            
        }
        
        //alert(settings.url);
        
        function _respone(){
        
            var v = $(_Obj).val();
            if (settings.last == v) 
            
                //alert("equire");
                return false;
            
            if (v == '') 
                return false;
            
            $.ajax({
                url: settings.uri,
                type: 'POST',
                data: 'post=1&action=post&value=' + v,
                error: function(e){
                    alert("error！");
                    return false;
                },
                success: function(r){
                
                    ///	alert(r);
                    
                    _complie(r);
                    
                    return true;
                    
                }
            });
            
        }
        
        function _bgiframe(){
        
            if ($.browser.msie && /6.0/.test(navigator.userAgent)) {
                s = $.extend({
                    top: 'auto',
                    left: 'auto',
                    width: 'auto',
                    height: 'auto',
                    opacity: true,
                    src: 'javascript:false;'
                }, s ||
                {});
                var prop = function(n){
                    return n && n.constructor == Number ? n + 'px' : n;
                }, html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="' + s.src + '"' + 'style="display:block;position:absolute;z-index:-1;' + (s.opacity !== false ? 'filter:Alpha(Opacity=\'0\');' : '') + 'top:' + (s.top == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')' : prop(s.top)) + ';' + 'left:' + (s.left == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')' : prop(s.left)) + ';' + 'width:' + (s.width == 'auto' ? 'expression(this.parentNode.offsetWidth+\'px\')' : prop(s.width)) + ';' + 'height:' + (s.height == 'auto' ? 'expression(this.parentNode.offsetHeight+\'px\')' : prop(s.height)) + ';' + '"/>';
                return this.each(function(){
                    if ($('> iframe.bgiframe', this).length == 0) 
                        this.insertBefore(document.createElement(html), this.firstChild);
                });
            }
            return this;
            
            
        }
        
        function _complie(r){
        
            // var pos = _findPos(_Obj);
            $("#" + settings.id).show();
            $("#" + settings.id).css({
                top: parseInt(_getAbsoluteTop($(_Obj).attr("id"))) + parseInt(_Obj.height()) + 5,
                left: _getAbsoluteLeft($(_Obj).attr("id")),
                width: parseInt(_Obj.width()) * 1.2,
                "z-index": "0",
                "position": "absolute",
                "background-color": "#FFFFFF"
            });
            
            $("#" + settings.id)._bgiframe();
            
            //$("#" + settings.id).bgiframe(); 
            
            
            
            
            var o = "";
            
            var i = 1;
            o += "<div><ul>";
            $(r).find('respone').each(function(){
                o += "<li id=\"" + i + "\">" + $(this).attr("result") + "</li>\n";
                i++;
            });
            
            settings.total = i;
            
            o += "</ul></div>";
            
            $("#" + settings.id).html(o);
            
            $("#" + settings.id).children('ul').children('li').mouseover(function(){
                $(this).addClass(settings.movein);
                $(this).removeClass(settings.moveout);
                
                settings.select = $(this).html();
                //	alert(settings.select);
            
            }).mouseout(function(){
                $(this).addClass(settings.moveout);
                $(this).removeClass(settings.movein);
                
                settings.select = "n";
                //	alert(settings.select);
            
            }).click(function(e){
                // alert($(this).html());
                _select($(this).html());
            });
            
            
            
            
            //    alert($("#" + settings.id).html());
        
        
        
        }
        
        function _select(v){
        
            //alert(v);
            //if (settings.select == "n") 
            //    return false;
            //alert($(s).parent().parent().html());
            
            //var t=$("li:visible");
            
            //	alert('test');
            //	alert(t);
            //alert(v);
            
            //   var t = $("#" + settings.id + " li." + settings.movein);
            // alert(t.val());
            
            
            $(_Obj).val(v);
            $("#" + settings.id).hide();
        }
        
        _initialize();
        
        return false;
        //        _respone();
    
    };
})(jQuery);
